/**
 * OAuth 模块 API
 * OAuth 应用管理相关接口（Beta）
 */

import { request, type ApiResponse, type RequestParamValue } from "../request";

// ============ 类型定义 ============

/**
 * OAuth 响应类型
 */
export type OAuthResponseType = "code" | "token" | "id_token token";

/**
 * 代码挑战方法
 */
export type CodeChallengeMethod = "plain" | "sha256" | "S256";

/**
 * 授权类型
 */
export type GrantType = "authorization_code" | "refresh_token";

/**
 * OAuth Token 响应
 */
export interface OAuthTokenResponse {
	access_token: string;
	refresh_token: string;
	expires_in: number;
	token_type: "Bearer";
}

/**
 * OAuth 授权参数
 */
export interface OAuthAuthorizeParams {
	client_id: string;
	response_type: OAuthResponseType;
	redirect_uri: string;
	scope?: string;
	state?: string;
	response_mode?: string;
	code_challenge?: string;
	code_challenge_method?: CodeChallengeMethod;
	organization_slug?: string;
	resource?: string;
}

/**
 * OAuth Token 请求体
 */
export interface OAuthTokenBody {
	grant_type?: GrantType;
	client_id?: string;
	client_secret?: string;
	code?: string;
	code_verifier?: string;
	redirect_uri?: string;
	refresh_token?: string;
	resource?: string;
	scope?: string;
}

/**
 * OAuth 撤销 Token 请求体
 */
export interface OAuthRevokeTokenBody {
	client_id: string;
	client_secret: string;
	refresh_token: string;
}

/**
 * 项目认领授权参数
 */
export interface OAuthProjectClaimParams {
	project_ref: string;
	client_id: string;
	response_type: OAuthResponseType;
	redirect_uri: string;
	state?: string;
	response_mode?: string;
	code_challenge?: string;
	code_challenge_method?: CodeChallengeMethod;
}

// ============ API 方法 ============

/**
 * 通过 OAuth 授权用户（Beta）
 * 注意：此端点返回 204 No Content，通常用于重定向
 */
export function authorizeUser(
	params: OAuthAuthorizeParams
): Promise<ApiResponse<Record<string, unknown>>> {
	return request.get<Record<string, unknown>>(
		"/v1/oauth/authorize",
		params as Record<string, RequestParamValue>
	);
}

/**
 * 交换授权码获取用户的访问令牌和刷新令牌（Beta）
 */
export function exchangeToken(
	data: OAuthTokenBody
): Promise<ApiResponse<OAuthTokenResponse>> {
	return request.post<OAuthTokenResponse>(
		"/v1/oauth/token",
		data
	);
}

/**
 * 撤销 OAuth 应用授权及其对应的令牌（Beta）
 */
export function revokeToken(
	data: OAuthRevokeTokenBody
): Promise<ApiResponse<Record<string, unknown>>> {
	return request.post<Record<string, unknown>>(
		"/v1/oauth/revoke",
		data
	);
}

/**
 * 通过 OAuth 授权用户并认领项目
 * 启动指定提供者的 OAuth 授权流程。认证成功后，用户可以认领指定项目的所有权
 */
export function authorizeProjectClaim(
	params: OAuthProjectClaimParams
): Promise<ApiResponse<Record<string, unknown>>> {
	return request.get<Record<string, unknown>>(
		"/v1/oauth/authorize/project-claim",
		params as Record<string, RequestParamValue>
	);
}

export default {
	authorizeUser,
	exchangeToken,
	revokeToken,
	authorizeProjectClaim
};
